/**
 * ReportResetedServiceImpl.java
 * @author
 * 作者 屈甲康 
 */
package org.jackysoft.service.impl;

import java.util.Iterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.entity.Department;
import org.jackysoft.entity.ReportReseted;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.ReportResetedService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ReportResetedServiceImpl extends
		AbstractStringIdServiceImpl<ReportReseted> implements
		ReportResetedService {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7834891233525992889L;
	final static Log logger = LogFactory.getLog(ReportResetedServiceImpl.class);

	public ReportResetedServiceImpl() {
		this.type = ReportReseted.class;
	}

	@Override
	public boolean checkResetable(Department dept, DateTime date) {
		String hql = String.format("from %s r where r.department.id='%s' "
				+ " and year(r.dueDate)=%d " + " and month(r.dueDate)=%d "
				+ " and day(r.dueDate)=%d", table(), dept.getId(),
				date.getYear(), date.getMonthOfYear(), date.getDayOfMonth());
		Iterator itr = query(hql).iterate();

		ReportReseted rd = (ReportReseted) (itr.hasNext() ? itr.next() : null);
		return rd == null ? false : true;
	}

	@Override
	public void toggleResetable(Department dept, DateTime date,
			boolean resetable) {
		String hql = null;
		if (!resetable) {

			hql = String
					.format("delete from %s  where department.id='%s' "
							+ " and year(dueDate)=%d "
							+ " and month(dueDate)=%d "
							+ " and day(dueDate)=%d", table(), dept.getId(),
							date.getYear(), date.getMonthOfYear(),
							date.getDayOfMonth());

			query(hql).executeUpdate();
			return;
		}
		
		hql = String
				.format("from %s r where r.department.id='%s' "
						+ " and year(r.dueDate)=%d "
						+ " and month(r.dueDate)=%d "
						+ " and day(r.dueDate)=%d"
						, table()
						, dept.getId()
						, date.getYear()
						, date.getMonthOfYear()
						, date.getDayOfMonth());
		
		Iterator itr = query(hql).iterate();
		ReportReseted rd = (ReportReseted) (itr.hasNext() ? itr.next() : null);
        if(rd!=null){
        	rd.setResetable(resetable);
            return;
        }
        rd = new  ReportReseted();
        rd.setDepartment(dept);
        rd.setDueDate(date);
        rd.setResetable(resetable);
        this.create(rd);
		
	}

}